package tech.edwardvan.springsecuritydemo.security.filter;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import tech.edwardvan.springsecuritydemo.security.common.SecurityConstant;
import tech.edwardvan.springsecuritydemo.security.util.JwtTokenUtil;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Jwt Token校验过滤器
 *
 * @author EdwardVan
 */
@RequiredArgsConstructor
@Slf4j
public class JwtTokenAuthenticationFilter extends OncePerRequestFilter {

    private final JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (checkToken(request) && validateToken(request)) {
            String token = request.getHeader(SecurityConstant.TOKEN_HEADER);
            SecurityContextHolder.getContext().setAuthentication(jwtTokenUtil.getAuthentication(token));
        } else {
            SecurityContextHolder.clearContext();
        }
        chain.doFilter(request, response);
    }

    /**
     * 校验Token是否在HTTP请求头中
     */
    private boolean checkToken(HttpServletRequest request) {
        String headerToken = request.getHeader(SecurityConstant.TOKEN_HEADER);
        return StrUtil.isNotBlank(headerToken);
    }

    /**
     * 校验Token是否有效
     */
    private boolean validateToken(HttpServletRequest request) {
        String headerToken = request.getHeader(SecurityConstant.TOKEN_HEADER);
        boolean verify = false;
        try {
            verify = jwtTokenUtil.verify(headerToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return verify;
    }
}
